<?php 
include("Base.php");

class User extends Base{
	
	/**
	 * 注册函数
	 * @param string $uname 用户名
	 * @param string $pwd 用户密码
	 * @param string $email 注册邮箱
	 * @param string $register_ip 注册ip
	 * @param string $callback_url 注册成功跳转链接
	 * @return
	 */
	public function register($uname='',$pwd='',$email='',$register_ip='',$OutletId=0)
	{

		if($uname==''||$pwd==''||$email==''||$register_ip=='') {
			$this->error("缺少必要注册信息")->end();
			return;
		}
		$db = new DB();
		if($db->getOne("SELECT uid FROM chu_user where email='".$email."'")){
			$this->error("邮箱已注册")->end();
			return;
		}
		if($db->getOne("SELECT uid FROM chu_user where uname='".$uname."'")){
			$this->error("用户名已被注册")->end();
			return;
		}
		$salt = substr(uniqid(rand()), 0, 6);
		$password_md5 = MD5(MD5($pwd).$salt);
		$sql = 'insert into chu_user(uname,upw,email,salt,register_ip,register_date,verify,role_id,region_id,Type) values("'.$uname.'","'.$password_md5.'","'.$email.'","'.$salt.'","'.$register_ip.'","'.time().'","0","6",'.$OutletId.',"最初级角色")';
		
		$re = $db->update($sql);
		$db->close();

		$token = md5($email.$uname);
		F($token,array('email'=>$email));
		SendMail($email,"激活账号","点击以下链接激活账号\r\n".HOST_PATH."/api.php?action=active&token=".$token);
		$this->message("请激活后登陆")->end();
	}
	/**
	 * 激活函数
	 * @param string $token token
	 * @return 
	 */
	public function active($token){
		$runt = F($token);
		// echo $runt;
		if(is_array($runt)){
			$email = $runt['email'];
			$sql = 'update chu_user set verify = "1" where email ="'.$email.'"';
			$db = new DB();
			$re = $db->update($sql);
			$db->close();
			F($token,null);
			header('Location:'.HOST_PATH."/home.html");
		}
		else{
			$this->error("链接不可用，已经验证或已过期")->end();
		}
	}
	/*
	 * 用户登陆函数
	 * 支持 uid/email/uname 登陆
	 */
	public function login($uname='',$upw='')
	{


		if ( empty($uname)||empty($upw) )
		{
			$this->error("用户名不许为空")->end();
			die;
		}

		$sql = 'SELECT * FROM chu_user ';
		$sql_salt = 'SELECT salt FROM chu_user ';

		//类型判断
		switch (true) {
			case ereg("^[1-9]*$",$uname):
				$sql .= " WHERE uid=".intval($uname);	
				$sql_salt .= " WHERE uid=".intval($uname);
				break;
			case ereg("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$",$uname):
				$sql .= " WHERE email='".$uname."'";
				$sql_salt .= " WHERE email='".$uname."'";
				break;
			case ereg("^[_.0-9a-z-]+$",$uname):
				$sql .= " WHERE uname='".$uname."'";
				$sql_salt .= " WHERE uname='".$uname."'";
				break;
			default:
				$this->error("用户标识不许为空")->end();
				die;
		}
	
		$db = new DB();
	
		//处理密码

		//$salt = $db->getOne($sql_salt)["salt"];
		$salt = $db->getOne($sql_salt);
		$upw = md5($upw.$salt["salt"]);
	
		$sql .= " AND upw='".$upw."'";
		//检查用户存不存在]
		$exist = $db->getOne($sql);
		if (count($exist) > 0 && $exist["verify"] != 0 )
		{
			unset( $exist["upw"] );
			unset( $exist["salt"] );

			$exist["token"] = makeGuid();

			$sql = "UPDATE chu_user SET token='".$exist["token"]."',last_ip='".$_SERVER['REMOTE_ADDR']."',last_login='".time()."' WHERE uid='".$exist["uid"]."'";
			$db->update($sql);
			$db->close();
			//用户存在
			$this->data($exist["token"]);
		}
		else {
			$db->close();
			$this->error("用户名或密码错误")->end();
			die;
		}
		$this->end();

	}

	/*
	 * 用户登陆函数
	 * 支持 uid/email/uname 登陆
	 *手机端用的登录接口，因为还需要传用户类型和菜单给用户
	 */
	public function loginPhone($uname='',$upw='')
	{


		if ( empty($uname)||empty($upw) )
		{
			$this->error("用户名不许为空")->end();
			die;
		}

		$sql = 'SELECT * FROM chu_user ';
		$sql_salt = 'SELECT salt FROM chu_user ';

		//类型判断
		switch (true) {
			case ereg("^[1-9]*$",$uname):
				$sql .= " WHERE uid=".intval($uname);	
				$sql_salt .= " WHERE uid=".intval($uname);
				break;
			case ereg("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}$",$uname):
				$sql .= " WHERE email='".$uname."'";
				$sql_salt .= " WHERE email='".$uname."'";
				break;
			case ereg("^[_.0-9a-z-]+$",$uname):
				$sql .= " WHERE uname='".$uname."'";
				$sql_salt .= " WHERE uname='".$uname."'";
				break;
			default:
				$this->error("用户标识不许为空")->end();
				die;
		}
	
		$db = new DB();
	
		//处理密码

		//$salt = $db->getOne($sql_salt)["salt"];
		$salt = $db->getOne($sql_salt);
		$upw = md5($upw.$salt["salt"]);
	
		$sql .= " AND upw='".$upw."'";
		//检查用户存不存在]
		$exist = $db->getOne($sql);
		if (count($exist) > 0 && $exist["verify"] != 0 )
		{
			unset( $exist["upw"] );
			unset( $exist["salt"] );

			$exist["token"] = makeGuid();

			$sql = "UPDATE chu_user SET token='".$exist["token"]."',last_ip='".$_SERVER['REMOTE_ADDR']."',last_login='".time()."' WHERE uid='".$exist["uid"]."'";
			$db->update($sql);
			
			//用户存在
			$arr=array();
			$arr['token']=$exist["token"];
			$arr['Type']=$exist["Type"];
			//"SELECT DISTINCT chu_menu.name  from chu_menu,chu_role,chu_role_menu where chu_menu.level=2 and chu_role_menu.menu_id=chu_menu.id and chu_role_menu.role_id=".$exist['role_id']
			$m=$db->query("SELECT DISTINCT chu_menu.name  from chu_menu,chu_role,chu_role_menu where chu_menu.level=2 and chu_role_menu.menu_id=chu_menu.id and chu_role_menu.role_id=".$exist['role_id']);
			$db->close();
			$arr['menu']=$m;
			$this->data($arr);
		}
		else {
			$db->close();
			$this->error("用户名或密码错误")->end();
			die;
		}
		$this->end();

	}
	//用户是否在线
	public function isOnline($token='')
	{
		if (empty($token)){
			$this->error("token值为空。")->end();
			die;
		}

		$sql = "SELECT uname FROM chu_user WHERE token='".$token."'";

		$db = new DB();
		$exist = $db->getOne($sql);
		$db->close();
		if($exist){
			//已经登录
			$this->data($exist);
		}
		else{
			$this->error("未登录");
		}
		$this->end();
	}

	//获取用户信息
	public function getUserInfo($token,$registerData=false,$loginData=false){
		$sql = 'SELECT *';
		// if($registerData) $sql.=",register_ip,register_date";
		// if($loginData) $sql.=",last_ip,last_login";
		$sql.=' FROM chu_user WHERE token="'.$token.'"';
		$db = new DB();
		$userInfo = $db -> getOne($sql);
		$db -> close();
		if($userInfo) $this->data($userInfo);
		else $this->error("无此用户！");
		$this->end();
	}
	//获取用户信息通过uid
	public function getUserInfoByuid($uid){
		$sql = "SELECT * FROM chu_user where uid=".$uid;
		$db = new DB();
		$userInfo = $db -> getOne($sql);
		$db -> close();
		if($userInfo) $this->data($userInfo);
		else $this->error("无此用户！");
		$this->end();
	}
	//注销
	public function logout($token='')
	{
		if ( empty($token) )
		{
			$this->error("token 值为空")->end();
			die;
		}
		$sql = "UPDATE chu_user SET token = '' WHERE token='".$token."'";
		$db = new DB();
		$ok = $db->update($sql);
		$db->close();
		$this->message("注销成功")->end();

	}

	//修改用户信息
	public function modify($token='', $data='')
	{
		if ( empty($token) )
		{
			$this->error("token 值为空")->end();
			die;
		}

		if ( !is_array($data) ){
			$this->error("数据值为空")->end();
			die;
		}

		$sql = "UPDATE  chu_user set ";
		foreach ($data as $key => $value) {
			if ( $key == "upw" || $key == "salt" || $key == "email"
				|| $key == "token" || $key == "verify")
				continue;
			$sql .= " ".$key."='".$value."' ";
		}
		$sql .= " WHERE token='".$token."'";
		$db = new DB();
		$ok = $db->update($sql);
		$db->close();
		$this->message("修改完成")->end();
	}
	/*
	//get menu
	public function getMenu($token){
		$db = new DB();
		$menuDbInfoGroup = array();
		$menuInnerInfo =array();
		$menuInfo=array();
		$sqlParent='SELECT id,name,url,pid,key_name,icon_class FROM chu_menu WHERE id in (';
		$sqlChild = 'SELECT name,url,pid,key_name FROM chu_menu 
		WHERE id IN
		(SELECT menu FROM chu_access WHERE id IN
		 (SELECT access_id FROM chu_role WHERE name IN
			 (SELECT role_id FROM chu_user WHERE token="'.$token.'")
		)
		) order by pid';
  
		$menuDbInfo = $db -> query($sqlChild);
		
		// $this->data($menuDbInfo)->end();
		// $sql='insert into chu_menu(name,url,pid) values("IP段列表","IPManager/overview","2")';
		// echo $db->update($sql);
		foreach ($menuDbInfo as $key => $value) {
			if(!isset($menuDbInfoGroup[$value['pid']])){
				array_unshift($pidArray,$value['pid']);
				$menuDbInfoGroup[$value['pid']]=array();
				$menuInnerInfo[$value['pid']]=array();
				$sqlParent.='"'.$value['pid'].'",';
			}
			
			array_unshift($menuDbInfoGroup[$value['pid']],$value);
		}
		$sqlParent = preg_replace('/,$/',")",$sqlParent);
		foreach ($menuDbInfoGroup as $k1 => $v1) {
			foreach ($v1 as $k2 => $v2) {
				$menuInnerInfo[$k1][$v2['key_name']] = array(
					'text' => $v2['name'],
        					'url'  =>  $v2['url']
					);
			}
		}
		$menuDbInfo = $db->query($sqlParent);
		foreach ($menuDbInfo as $key => $value) {
			
			if (!isset($menuInfo[$value['key_name']]['children'])){
				// echo 'haha';
				$menuInfo[$value['key_name']]['children'] = array();
			}
			$menuInfo[$value['key_name']] = array(
				'text' => $value['name'],
				'url' => $value['url'],
				'icon_class' => $value['icon_class'],
				'children' => $menuInnerInfo[$value['id']],
				);
			// echo $value['pid'];
		}
		$this->data($menuInfo)->end();
		
	}*/



	//返回错误
	public function showError()
	{
		$this->error("没有找到该方法")->end();
	}

	//得到网点的客户列表
	public function getClientList($token){
		$db = new DB();
		$user=$db->getOne("SELECT * from chu_user where token='".$token."'");
		$region_id=$user['region_id'];
		$region=$db->getOne("SELECT region_type from chu_region where region_id=".$region_id);
		$region_type=$region['region_type'];
		$sql="";
		if($region_type==3)
			$sql="SELECT chu_user.uname,chu_user.uid,chu_user.email,chu_user.register_date,chu_user.last_login,chu_region.region_name regionname from chu_user,chu_region where chu_user.region_id=chu_region.region_id and  chu_user.Type='客户' and chu_user.region_id=".$region_id." and chu_user.uid !=".$user['uid'];
		if($region_type==2)
			$sql="SELECT chu_user.uname,chu_user.uid,chu_user.email,chu_user.register_date,chu_user.last_login,chu_region.region_name regionname from chu_user,chu_region where chu_user.region_id=chu_region.region_id and chu_user.Type='客户'  and chu_user.uid !=".$user['uid']." and chu_user.region_id in (SELECT  region_id from chu_region where region_id=".$region_id." or parent_id=".$region_id.")";
		if($region_type==1)
			$sql="SELECT chu_user.uname,chu_user.uid,chu_user.email,chu_user.register_date,chu_user.last_login,chu_region.region_name regionname from chu_user,chu_region where chu_user.region_id=chu_region.region_id and chu_user.Type='客户'  and chu_user.uid !=".$user['uid']." and chu_user.region_id in (SELECT  region_id from chu_region  where region_id=".$region_id." or parent_id=".$region_id."  union (select region_id from chu_region where parent_id in (select region_id from chu_region where parent_id=".$region_id.")))";

		$clientList=$db->query($sql);
		//$clientList=$db->query("SELECT * from chu_user where region_id=".$region_id);
		//处理数据集
		//$count=count($clientList);
		$data=array();
		$table=array();
		$table['checkall']=false;
		$thead=array();
		$thead['uname']="用户名";
		$thead['regionname']="地区";
		$thead['email']="邮箱";
		$thead['register_date']="注册日期";
		$thead['last_login']="上次登录时间";
		$table['thead']=$thead;
		$tr=array();
		$i=1;
		foreach ($clientList as $value) {
			$arr1=array();
			foreach ($value as $k => $v) {
				if($k=="register_date"||$k=="last_login")
					$arr1[$k]=date("Y/m/d",$v);
				else
					$arr1[$k]=$v;				
				
			}
			$tr[$i]=$arr1;
			$i=$i+1;
		}
		$table['tr']=$tr;
		$operate=array();
		$operate['detail']=true;
		$operate['lineList']=true;
		$table['operate']=$operate;
		$data['table']=$table;
		$data['item_count']="".($i-1);

		$db->close();
		$this->data($data)->end();
	}

	//得到地区信息
	public function getRegion($region_id,$region_type){
		$db=new DB();
		//拿省一级的
		if($region_type==1||$region_type=='1'){
			$data=$db->query("SELECT * from chu_region where region_name='湖北'");
			$this->data($data)->end();
		}
		else{
			$data=$db->query("SELECT * from chu_region where region_type=".$region_type." and parent_id=".$region_id);
			$data[]=array("region_id"=>-1,"region_name"=>"空");
			//p($data);die;
			$this->data($data)->end();
		}
	}
	public function checkname($name)
	{
		$db=new DB();
		$sql="select * from chu_user where uname='".$name."'";
		///p($sql); die; 
		
		$data=$db->query($sql);

		$this->data($data)->end();
	}
	public function checkLineByName($name)
	{
		$db=new DB();
		
		$sql="select * from chu_line where Name='".$name."'";
	// 	$name="chujie";
	// $sql="select * from chu_user where uname='".$name."'";
		//$result = mysql_query($sql,$this->conn);
		
		$data=$db->query($sql);
		$this->data($data)->end();
	}
}
?>